import React, {useState, useCallback} from 'react'
import {Row, Input} from 'antd'
import {Redirect} from 'react-router-dom'
import {isValidKey, isValidValue, getValue} from './lib/password.js'

export default ({history}) => {
  const [value, setValue] = useState('')
  const onChange = e => {
    const tvalue = e.target.value
    setValue(tvalue)
    if(isValidKey(tvalue)) {
      localStorage.setItem('myclass', getValue(tvalue))
      history.push('/play', {classname: getValue(tvalue)})
    }
  }
  const inputRef = useCallback(node => {
    if(node != null) {
      node.focus()
    }
  }, [])
  const myclass = localStorage.getItem('myclass')
  if(isValidValue(myclass)) {
    return (
      <Redirect to={{
        pathname: '/play',
        state: {classname: myclass}
      }}/>
    )
  }
  return (
    <Row align="middle" justify="center" type="flex"
         style={{minHeight: '100vh', margin: 10}}>
      <div style={{display: 'inline-block'}}>
        <Input placeholder="口令"
               onChange={onChange}
               value={value}
               ref={inputRef}/>
      </div>
    </Row>
  )
}
